
#include "cardviewer.h"

#include "cardviewwidget.h"

#include "sqlite3stmt.h"

/* 
 *  Constructs a CardViewer which is a child of 'parent', with the 
 *  name 'name' and widget flags set to 'f' 
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
CardViewer::CardViewer( int c, sqlite3* s, QWidget* parent,  const char* name, bool modal, Qt::WFlags fl )
    : QDialog( parent, name, modal, fl ),
      sql(s),
      cards_n(c)
{
  setupUi(this);

  QString r;
  r = "SELECT dname FROM decks;";

  for(sqlite3Stmt stmt(sql,r) ; !stmt.done() ; stmt.step()) {
    cbDeck->insertItem(stmt.column_text(0));
  }
    
  r = "SELECT card_ver.card, decks.dname, releases.rname, cards.comments";
  r += " FROM card_ver, decks, cards, releases";
  r += " WHERE releases.rnum=card_ver.ver AND card_ver.rowid==cards.printing AND decks.dnum==cards.deck AND cards.cnum=="+QString::number(cards_n)+";";

  sqlite3Stmt stmt(sql,r);
  if(!stmt.done()) {
    top_view_widget->load(stmt.column_int(0),sql);   // Tell the subviewer the card_t associated with this card
    
    cbDeck->setCurrentItem(cbDeck->findText(stmt.column_text(1)));
    
    top_view_widget->cbPrinting->setCurrentItem(top_view_widget->cbPrinting->findText(stmt.column_text(2)));
    
    leCondition->setText(stmt.column_text(3));
  }
}

/*  
 *  Destroys the object and frees any allocated resources
 */
CardViewer::~CardViewer()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void CardViewer::languageChange()
{
    retranslateUi(this);
}

/*
 * public slot
 */
void CardViewer::save_data()
{
  top_view_widget->save();

  QString s;
  s = "UPDATE cards ";
  s += "SET printing = ";
  s +=       "(SELECT card_ver.rowid ";
  s +=        "FROM releases, card_ver ";
  s +=        "WHERE card_ver.card="+QString::number(top_view_widget->card_t_n)+" AND card_ver.ver=releases.rnum AND releases.rname='"+top_view_widget->cbPrinting->currentText()+"'), ";
  s +=     "deck = ";
  s +=       "(SELECT decks.dnum ";
  s +=        "FROM decks ";
  s +=        "WHERE decks.dname='"+cbDeck->currentText().replace('\'',"''")+"'), ";
  s +=     "comments = '"+leCondition->text().replace('\'',"''")+"'";
  s += "WHERE cnum="+QString::number(cards_n)+";";
  if(sqlite3_exec(sql,s,0,0,0))
    qWarning("Could not update card %d(%s): %s",cards_n,s.ascii(),sqlite3_errmsg(sql));

  accept();
}


